#Copyright (C) Nial Peters 2013
#
#This file is part of pydoas.
#
#pydoas is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#pydoas is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with pydoas.  If not, see <http://www.gnu.org/licenses/>.

import wx
from wx.lib.buttons import GenBitmapToggleButton as GenBitmapToggleButton
import os.path

from avoplot.persist import PersistentStorage
from avoplot.plugins import AvoPlotPluginSimple
from avoplot.subplots import RealtimeXYSubplot
from avoplot.series import RealtimeXYDataSeries
from avoplot import controls
import doas.ooi

from doas.io import SpectrumIO, UnableToLoad

plugin_is_GPL_compatible = True


class LiveSpectrumControlPanel(controls.AvoPlotControlPanelBase):
    def __init__(self, series):
        
        self.series = series
        super(LiveSpectrumControlPanel, self).__init__('Spectrometer')
    
    
    def setup(self, parent):
        
        super(LiveSpectrumControlPanel, self).setup(parent)
        
        button_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.play_button = GenBitmapToggleButton(self, -1, wx.ArtProvider.GetBitmap("avoplot_play", wx.ART_BUTTON))
        self.play_button.SetBitmapSelected(wx.ArtProvider.GetBitmap("avoplot_pause", wx.ART_BUTTON))
        self.play_button.SetToggle(True)
        button_sizer.Add(self.play_button,0,wx.ALIGN_CENTER)
        wx.EVT_BUTTON(self, self.play_button.GetId(), self.on_pause)
        
        self.record_button = GenBitmapToggleButton(self, -1, wx.ArtProvider.GetBitmap("avoplot_record", wx.ART_BUTTON))
        button_sizer.Add(self.record_button,0,wx.ALIGN_CENTER_HORIZONTAL)
        
        self.Add(button_sizer,0,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL)
        
        
        sizer = wx.FlexGridSizer(0,2,5,0)
        
        sizer.Add(wx.StaticText(self, -1, "Spectra to Average:"))
        self.n_avg_box = wx.SpinCtrl(self, -1, initial=self.series.spectrometer.n_avg, min=1, max=1000)
        sizer.Add(self.n_avg_box)
        
        wx.EVT_SPINCTRL(self, self.n_avg_box.GetId(), self.on_n_avg)
        #wx.EVT_BUTTON(self, normalise_button.GetId(), self.on_normalise)
        
        sizer.Add(wx.StaticText(self, -1, "Integration time (ms):"))
        self.int_time_box = wx.SpinCtrl(self, -1, initial=self.series.spectrometer.int_time_millisec, min=2, max=10000)
        sizer.Add(self.int_time_box)
        wx.EVT_SPINCTRL(self, self.int_time_box.GetId(), self.on_int_time)
        
        self.Add(sizer,1,wx.EXPAND)
        
    
    def on_pause(self, evnt):      
        self.series.pause_update(not self.play_button.GetToggle())

    
    def on_int_time(self, evnt):
        int_time = self.int_time_box.GetValue()
        self.series.spectrometer.int_time_millisec = int_time
        
    
    def on_n_avg(self, evnt):
        n_avg = self.n_avg_box.GetValue()
        self.series.spectrometer.n_avg = n_avg



class LiveSpectrumSeries(RealtimeXYDataSeries):
    def __init__(self, spectrometer):
        
        self._spectrometer = spectrometer
        super(LiveSpectrumSeries,self).__init__(spectrometer.serial_number)
        self.add_control_panel(LiveSpectrumControlPanel(self))
        
    @property
    def spectrometer(self):
        return self._spectrometer
    
    @staticmethod    
    def get_supported_subplot_type():
        return LiveSpectrumSubplot
    
    def delete(self):
        super(LiveSpectrumSeries,self).delete()
        self._spectrometer.close()
    
    
    def update_series(self):
        
        spec = self._spectrometer.get_spectrum()
        
        self.set_xy_data(spec.wavelengths, spec.counts)


class LiveSpectrumSubplot(RealtimeXYSubplot):
    def my_init(self):
        super(LiveSpectrumSubplot,self).my_init()
        
        ax = self.get_mpl_axes()
        ax.set_ylim((0, 65536))
        ax.set_xlim((200,500))


class SpectrumCollectionPlugin(AvoPlotPluginSimple):
    def __init__(self):
        AvoPlotPluginSimple.__init__(self,"Spectrum Collection Plugin", LiveSpectrumSeries)
        
        self.set_menu_entry(['DOAS','Collection'], "Record spectra in realtime from an OceanOptics spectrometer")
    
    
    def plot_into_subplot(self, subplot):
        
        #spectrometers = oceanoptics.get_available_spectrometers()
        spectrometers = doas.ooi.list_spectrometers()
        
        if not spectrometers:
            wx.MessageBox("No available spectrometers found.", 
                          "AvoPlot", wx.ICON_ERROR)
            return False
        
        for s in spectrometers:
            spectro = doas.ooi.get_first_available_spectrometer()
            data_series = LiveSpectrumSeries(spectro)
            
            subplot.add_data_series(data_series)
            
            data_series.start_plotting()
        
        return True
    